package com.joke.mydiary.fragment;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.preference.PreferenceManager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.telephony.TelephonyManager;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.joke.mydiary.DaoImpl.DiaryDao;
import com.joke.mydiary.R;
import com.joke.mydiary.RemindManagerActivity;
import com.joke.mydiary.ShowDiaryActivity;
import com.joke.mydiary.pojo.Diary;
import com.joke.mydiary.service.BackupIntentService;
import com.joke.mydiary.utils.ChectNetUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class ListDiaryFragment extends Fragment implements View.OnClickListener, LoaderManager.LoaderCallbacks<Cursor> {

    private ListView listDiary;
    private Button btnNewDiary;
    private ListDiaryListener mListener;
    private SimpleCursorAdapter dataAdapter;


    public ListDiaryFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list_diary, container, false);
        listDiary = (ListView) view.findViewById(R.id.listDiary);
        btnNewDiary = (Button) view.findViewById(R.id.btnNewDiary);
        btnNewDiary.setOnClickListener(this);


        dataAdapter = new SimpleCursorAdapter((Context) mListener, R.layout.item_diary_layout,
                mListener.getDiaryDao().findAllCursor(),
                new String[]{"date", "content"}, new int[]{R.id.txtListDate, R.id.txtListContent}
                , SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        listDiary.setAdapter(dataAdapter);
        getLoaderManager().initLoader(0, null, this);

        listDiary.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cursor = (Cursor) parent.getItemAtPosition(position);
                //封装Diary对象
                if (cursor.moveToPosition(position)) {
                    Diary diary = null;
                    try {
                        diary = new Diary();
                        diary.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
                        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(cursor.getString(cursor.getColumnIndex("date")));
                        diary.setDate(date);
                        diary.setContent(cursor.getString(cursor.getColumnIndex("content")));
                        diary.setImagePath(cursor.getString(cursor.getColumnIndex("image_path")));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    Intent intent = new Intent((Context) mListener, ShowDiaryActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("diary", diary);
                    intent.putExtra("bundle", bundle);
                    startActivity(intent);
                }
            }
        });
        //注册上下文菜单
        registerForContextMenu(listDiary);
        return view;
    }


    @Override
    public void onResume() {
        refresh();
        super.onResume();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (ListDiaryListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        getActivity().getMenuInflater().inflate(R.menu.menu_context, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        TextView txDate = (TextView) info.targetView.findViewById(R.id.txtListDate);
        TextView txContent = (TextView) info.targetView.findViewById(R.id.txtListContent);
        switch (item.getItemId()) {
            case R.id.action_backup:
                //首先检查网络是否可用
                boolean flag = new ChectNetUtil().isNetWorkConnected(getActivity());
                if (flag) {
                    //可用，启动服务，备份
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    boolean isOpend = sp.getBoolean("isOpend_preference", false);
                    if (isOpend) {
                        //获取云备份信息
                        TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
                        String phone = tm.getLine1Number();
                        String username = sp.getString("username_preference", phone);
                        String uriPath = sp.getString("ip_preference", "127.0.0.1");

                        //备份
                        Diary diary = mListener.getDiaryDao().findByTime(txDate.getText().toString());
                        Intent backupIntent = new Intent(getActivity(), BackupIntentService.class);
                        backupIntent.putExtra("diary", diary);
                        backupIntent.putExtra("userName", username);
                        backupIntent.putExtra("uriPath",uriPath);
                        mListener.startBackupService(backupIntent);
                    } else {
                        //没有打开云备份设置
                        Toast.makeText(getActivity(), "请在设置中打开云备份选项!", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    //不可用，提示用户
                    Toast.makeText(getActivity(), "网络不可用，无法备份", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.action_remind:
                //启动设置提醒的界面
                Intent intent = new Intent(getActivity(), RemindManagerActivity.class);
                intent.putExtra("content", txContent.getText().toString());
                startActivity(intent);
                break;
            case R.id.action_delete:
                mListener.deleteByMenu(txDate.getText().toString());
                refresh();
                break;
        }
        return super.onContextItemSelected(item);
    }


    public void refresh() {
        getLoaderManager().restartLoader(0, null, this);
    }

    /**
     * 用于搜索时设置数据
     *
     * @param cursor
     */
    public void searchData(Cursor cursor) {
        dataAdapter.swapCursor(cursor);
    }

    /**
     * 按钮事件处理
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnNewDiary) {
            mListener.showAddDiaryFragment();
        }

    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Uri uri = Uri.parse("content://com.joke.mydiary.provider/diaries");
        CursorLoader cursorLoader = new CursorLoader((Context) mListener, uri, null, null, null, "_id DESC");
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        dataAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        dataAdapter.swapCursor(null);
    }

    /**
     * fragment的回调方法
     */
    public interface ListDiaryListener {
        // TODO: Update argument type and name
        public DiaryDao getDiaryDao();

        public void showAddDiaryFragment();

        public boolean deleteByMenu(String time);

        public void startBackupService(Intent intent);


    }

}
